package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import modelo.Cliente;

public class ClienteDao {
	
	private Connection conexao;
	
	public ClienteDao(Connection con) throws ClassNotFoundException {
		this.conexao = con;		
	}
	
	public Cliente getCliente(int codigo) {		
		Cliente c = null;		
		PreparedStatement stm = null;
		try {
			stm = conexao.prepareStatement("select * from cliente " +  
										   "where codigo = ?");
			stm.setInt(1, codigo);			
			ResultSet rs = stm.executeQuery();
			while (rs.next()) {
				c = setDados(rs);
			}						
		} catch (SQLException sqlEx) {
			sqlEx.printStackTrace();
		}
		return c;		
	}
	
	public Cliente getCliente(String nome) {		
		Cliente c = null;		
		PreparedStatement stm = null;
		try {
			stm = conexao.prepareStatement("select * from cliente " +  
										   "where nome = ?");
			stm.setString(1, nome);			
			ResultSet rs = stm.executeQuery();
			while (rs.next()) {
				c = setDados(rs);
			}						
		} catch (SQLException sqlEx) {
			sqlEx.printStackTrace();
		}
		return c;		
	}
	
	public List<Cliente> getCliente() {		
		Cliente c = null;
		List<Cliente> listaClientes = null;		
		PreparedStatement stm = null;
		try {
			stm = conexao.prepareStatement("select * from cliente");						
			ResultSet rs = stm.executeQuery();
			while (rs.next()) {
				c = setDados(rs);
				if(!(c == null) ) {
					if(listaClientes == null) {
						listaClientes = new ArrayList<Cliente>();
					}
					listaClientes.add(c);
				}								
			}						
		} catch (SQLException sqlEx) {
			sqlEx.printStackTrace();
		}
		return listaClientes;		
	}
	
	private Cliente setDados(ResultSet rs) throws SQLException{
		Cliente cliente = new Cliente();
		cliente.setCdCliente(rs.getInt("codigo"));
		cliente.setDsCliente(rs.getString("nome"));	
		return cliente;		
	}

}
